﻿using Xejen.Hosting;
using Xejen.Hosting.Extensions;
using Xejen.Logger;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Text;

namespace Xejen.Ipc.Framework.Extensions
{
    /// <inheritdoc cref="IIpcBuilder"/>
    internal class IpcBuilder : IIpcBuilder
    {
        private readonly IAppHost _host;
        private readonly ILogger _logger;
        private readonly IConfiguration _configuration;
        private readonly ILoggerManager _loggerManager;
        private readonly IpcHostConfig _ipcHostConfig = new IpcHostConfig();

        /// <inheritdoc cref="IpcBuilder"/>
        /// <param name="host"><inheritdoc cref="IAppHost" path="/summary"/></param>
        public IpcBuilder(IAppHost host)
        {
            Check.NotNull(host, nameof(host));

            _host = host;
            _configuration = host.Configuration;
            _loggerManager = host.LoggerManager;
            _logger = _loggerManager.CreateLogger<IpcBuilder>();
        }

        /// <inheritdoc/>
        public IIpcBuilder ConfigureIpcConfiguration(Action<IpcHostConfig> configure)
        {
            _configuration.Bind(nameof(IpcHostConfig), _ipcHostConfig);

            configure?.Invoke(_ipcHostConfig);

            _host.AddServices((services) =>
            {
                services.AddSingleton(_ipcHostConfig);
            });

            _logger.LogInformation($"完成{nameof(IpcHostConfig)}配置：{{@value}}", _ipcHostConfig);

            return this;
        }

        /// <inheritdoc/>
        public IIpcBuilder AddIpcHost()
        {
            _host.AddServices((services) =>
            {
                services.AddSingleton<IIpcHost>(IpcHost.CreateHost(_ipcHostConfig, _loggerManager));
            });

            _logger.LogInformation($"完成工业控制流程的主机构建");

            return this;
        }
    }
}
